<?php

class Application_Model_LaptopMapper{

	protected $_dbTable;

	public function setDbTable($dbTable)
	{
		if (is_string($dbTable)) {
			$dbTable = new $dbTable();
		}
		if (!$dbTable instanceof Zend_Db_Table_Abstract) {
			throw new Exception('Invalid table data gateway provided');
		}
		$this->_dbTable = $dbTable;
		return $this;
	}

	public function getDbTable()
	{
		if (null === $this->_dbTable) {
			$this->setDbTable('Application_Model_DbTable_Laptop');
		}
		return $this->_dbTable;
	}
	
	public function save(Application_Model_Laptop $laptop){
	
		
	
		$computerMapper = new Application_Model_ComputerMapper();
		$row = $computerMapper->save($laptop);
		$laptop->setComputerId($row);
	
		$data = array(
				'id_computer' 		=> $laptop->getComputerId(),
				'screensize'		=> $laptop->getScreensize(),
		);
	
		if (null === ($id = $laptop->getLaptopId())) {
			unset($data['id_laptop']);
			return $this->getDbTable()->insert($data);
		} else {
			$this->getDbTable()->update($data, array('id_laptop = ?' => $id));
			return $id;
		}
	}
	
	public function find($id, Application_Model_Laptop $laptop)
	{
		$result = $this->getDbTable()->find($id);
		if (0 == count($result)) {
			return;
		}
		$row = $result->current();
		$laptop->setLaptopId($row->id_laptop);
		$laptop->setComputerId($row->id_computer);
		$laptop->setScreensize($row->screensize);
	
		$computerMapper = new Application_Model_ComputerMapper();
		$laptop = $computerMapper->find($laptop->getComputerId(), $laptop);
	
		return $laptop;
	}
	
	public function delete($id)
	{
	
		$laptop= new Application_Model_Laptop();
		$computerMapper = new Application_Model_ComputerMapper();
		$laptop = $this->find($id, new Application_Model_Laptop());
	
		$result = $this->getDbTable()->find($id);
		if (0 != count($result)) {
			$this->getDbTable()->delete(array('id_laptop = ?' => $id));
		}
	
		$computerMapper->delete($laptop->getComputerId());
	
	
	}
	
	public function indexBuilder(Zend_Search_Lucene_Document $doc, Application_Model_Laptop $laptop)
	{
		$computerMapper = new Application_Model_ComputerMapper();
		$doc->addField(Zend_Search_Lucene_Field::Text('screensize', $laptop->getScreensize(), 'utf-8'));
		$doc->addField(Zend_Search_Lucene_Field::Text('objectType', 'laptop', 'utf-8'));
		$doc = $computerMapper->indexBuilder($doc, $laptop);
		
		return $doc;
	}
}